package com.lancoo.edu.platform.operation.backupRestore.service.bo.foreign;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.lancoo.edu.platform.operation.backupRestore.domain.bo.BrServerSysSaveBo;
import com.lancoo.edu.platform.operation.backupRestore.domain.po.BrServerSysInfo;
import com.lancoo.edu.platform.operation.backupRestore.service.po.BrServerSysInfoService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lzh
 * @Date 2024/4/7 14:45
 */
@Service
@AllArgsConstructor
public class BrForeignBoService {

    private final BrServerSysInfoService brServerSysInfoService;

    /**
     * 保存服务器系统信息
     *
     * @param saveBoList 服务器系统信息保存接收实体
     */
    public void saveServerSys(List<BrServerSysSaveBo> saveBoList) {
        // 1、查询指定教育局的数据
        List<BrServerSysInfo> brServerSysInfoList = brServerSysInfoService.list();
        // 2、为空保全部
        if (CollectionUtil.isEmpty(brServerSysInfoList)) {
            brServerSysInfoList = BeanUtil.copyToList(saveBoList, BrServerSysInfo.class);
            brServerSysInfoService.saveBatch(brServerSysInfoList);
            return;
        }
        // 3、不为空，已经保存的赋值存在的主键ID
        Map<String, Integer> sysMapId = brServerSysInfoList.stream().collect(Collectors.groupingBy(BrServerSysInfo::getSysId, Collectors.mapping(BrServerSysInfo::getId, Collectors.summingInt(Integer::intValue))));
        saveBoList.stream()
                .filter(serverSysSaveBo -> sysMapId.containsKey(serverSysSaveBo.getSysId()))
                .forEach(serverSysSaveBo -> serverSysSaveBo.setId(sysMapId.getOrDefault(serverSysSaveBo.getSysId(),null)));
        // 4、更新保存
        brServerSysInfoList = BeanUtil.copyToList(saveBoList, BrServerSysInfo.class);
        brServerSysInfoService.saveOrUpdateBatch(brServerSysInfoList);
    }
}
